import axios, {AxiosInstance, AxiosRequestConfig} from 'axios'

declare global {
  interface Window {
    api?: {
      request: (options: {
        url: string
        method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
        data?: any
        params?: any
        headers?: Record<string, string>
      }) => Promise<any>
    }
  }
}

const axiosClient: AxiosInstance = axios.create({
  baseURL: '/',
})

export async function httpRequest<T = any>(config: AxiosRequestConfig & { useElectron?: boolean }): Promise<T> {
  const { url = '', method = 'GET', data, params, headers } = config

  // 将 Axios 的 headers 归一化为 Record<string, string>
  const normalizeHeaders = (h: any): Record<string, string> | undefined => {
    if (!h) return undefined
    try {
      const entries = Object.entries(h as Record<string, any>)
      return Object.fromEntries(entries.map(([k, v]) => [k, String(v)]))
    } catch {
      return undefined
    }
  }
  const normalizedHeaders = normalizeHeaders(headers)

  // 优先使用 Electron 主进程代理，避免跨域
  if (window.api?.request) {
    return window.api.request({ url, method: method as any, data, params, headers: normalizedHeaders })
  }

  // 开发环境通过 Vite proxy 解决跨域
  const res = await axiosClient.request<T>({ url, method, data, params, headers })
  return res.data as T
}